<?php
/**
 * Class name is ConfigBaseSearch * @package backend\modules\common\controllers;
 * @author  Womtech  email:chareler@163.com
 * @DateTime 2020-04-15 01:50 
 */

namespace common\models\config;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use yii\db\ActiveQuery;
use yii\db\Expression;
use yii\helpers\ArrayHelper;
use common\models\config\ConfigBase;
use yii\base\DynamicModel;

/**
 * ConfigBaseSearch represents the model behind the search form about `common\models\config\ConfigBase`.
 */
class ConfigBaseSearch extends ConfigBase
{
    const EMPTY_STRING = "(空字符)";
    const NO_EMPTY = "(非空)";
    const SCENARIO_EDITABLE = 'editable';
    const SCENARIO_SEARCHE = 'search';

    public $start;
    public $end;
    public $pageSize;
    public $page;

    public function scenarios()
    {
        return ArrayHelper::merge(parent::scenarios(), [
            self::SCENARIO_EDITABLE => ['title','name','description','sort'],
            self::SCENARIO_SEARCHE => ['start','end','title'],
        ]);
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'sort', 'created_id', 'updated_id'], 'integer'],
            [['title', 'name', 'app_id', 'type', 'extra', 'description', 'is_hide_des', 'default_value', 'status'], 'safe'],
            [['created_at', 'updated_at'], 'match', 'pattern' => '/^.+\s\-\s.+$/'],
            // 在"register" 场景下 username, email 和 password 必须有值
            //[['start', 'end'],  'match', 'pattern' => '/^.+\s\-\s.+$/', 'on' => 'search'],
            [['start', 'end'],  'date','format'=>'yyyy-MM-dd', 'on' => 'search'],
            [['pageSize','page'], 'integer', 'on' => 'search'],

            

        ];
    }
    /**
     * 创建时间  如果不需要或者该数据模型 没有 created_at 字段，您应该删除
     * @return array|false|int
     */
    public function getCreatedAt()
    {
        if(empty($this->created_at)){
            return null;
        }
        $createAt = is_string($this->created_at)?strtotime($this->created_at):$this->created_at;
        if(date('H:i:s', $createAt)=='00:00:00'){
            return [$createAt, $createAt+3600*24];
        }
        return $createAt;
    }
    
    /**
     * Creates data provider instance with search query applied
     * @param array $params
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        /* $start = $params['start'];
        $end = $params['end']; */
        $query = self::find();



        $this->load($params,'');
        //if(!$this->validate(['start','end'])){
        if(!$this->validate()){
            return ;
        }
       
        /* $start = $params['start'];
        $validator = new yii\validators\DateValidator();
        //$validator = new yii\validators\EmailValidator();
        
        if ($validator->validate($start, $error)) {
            //echo '有效的日期格式';

        } else {
            //echo $error;
        } */


        //$this->load(['ConfigBase'=>$params]);
        /* empty(yii::$app->request->post('pageSize')) or $pageSize = 10;
        empty(yii::$app->request->post('page')) or $page = 1; */
        //$pageSize = !empty(yii::$app->request->post('pageSize')) ? (int)yii::$app->request->post('pageSize') : yii::$app->params['pageSize'];
        //!empty($this->pageSize) or $this->pageSize =yii::$app->params['pageSize'] ;//equal if(empty($this->pageSize)){$this->pageSize =yii::$app->params['pageSize'];}
        if(empty($this->pageSize)){$this->pageSize =yii::$app->params['pageSize'];}
        $this->page =  !empty($this->page) ? (int)$this->page-1 : 0;
        //验证分页参数格式,limit和page为数字
        /* if(!empty($start)){
            $startTime = strtotime($start. " 00:00:00");
            $query->andWhere(['>=','created_at',$startTime]);
        } */
        /* if(!empty($end)){
            $endTime = strtotime($end. " 23:59:59");
            $query->andWhere(['<=','created_at',$endTime]);
        } */

        if ( !empty($this->start) ) {
            $start=$this->start;
            //验证是否为日期格式,如果是,则转化为时间戳,并加入筛选中
            $validator = new yii\validators\DateValidator();
            $validator->format ='yyyy-MM-dd';
            //$startTime = strtotime($start. " 00:00:00");
            //$startTime = $start;
            if ($validator->validate($start, $error)) {
                //echo '有效的日期格式'; 
                $startTime = strtotime($start. " 00:00:00");
                $query->andFilterWhere(['>=', 'created_at', $startTime]);
            }
            //list($s, $e) = explode(' - ', $this->created_at);           
        }

        if ( !empty($this->end) ) {
            $end = $this->end;
            //验证是否为日期格式,如果是,则转化为时间戳,并加入筛选中
            $validator = new yii\validators\DateValidator();
            $validator->format ='yyyy-MM-dd';
            if ($validator->validate($end, $error)) {
                $endTime = strtotime($end. " 23:59:59");
                $query->andFilterWhere(['<=', 'created_at', $endTime]);
            }           
        }



        /* if ( ! is_null($this->updated_at) && strpos($this->updated_at, ' - ') !== false ) {
            list($s, $e) = explode(' - ', $this->updated_at);
            $query->andFilterWhere(['between', 'updated_at', strtotime($s), strtotime($e)]);
        } */
        
        $query->andFilterWhere([
            'id' => $this->id,
            'sort' => $this->sort,
            'created_id' => $this->created_id,
            'updated_id' => $this->updated_id,
        ]);
        $this->filterLike($query, 'title');
        /* $this->filterLike($query, 'name');
        $this->filterLike($query, 'app_id');
        $this->filterLike($query, 'type');
        $this->filterLike($query, 'extra');
        $this->filterLike($query, 'description');
        $this->filterLike($query, 'is_hide_des');
        $this->filterLike($query, 'default_value');
        $this->filterLike($query, 'status'); */
        $dataProvider = new ActiveDataProvider([
            'pagination' => [
                'pageSize' => $this->pageSize,
                'page' => $this->page,

            ],
            'query' => $query,
            'sort' => ['defaultOrder' => ['id' => SORT_DESC]],
            ]); 
        if (!$this->validate()) {
            return $dataProvider;
        }
        return $dataProvider;
    }

    /**
     * @param ActiveQuery $query
     * @param $attribute
     */
    protected function filterLike(&$query, $attribute)
    {
        $this->$attribute = trim($this->$attribute);
        switch($this->$attribute){
            case \Yii::t('app', '(not set)'):
                $query->andFilterWhere(['IS', $attribute, new Expression('NULL')]);
                break;
            case self::EMPTY_STRING:
                $query->andWhere([$attribute => '']);
                break;
            case self::NO_EMPTY:
                $query->andWhere(['IS NOT', $attribute, new Expression('NULL')])->andWhere(['<>', $attribute, '']);
                break;
            default:
                $query->andFilterWhere(['like', $attribute, $this->$attribute]);
                break;
        }
    }
}
